package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import org.apache.http.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN_URL="https://api.weixin.qq.com/sns/jscode2session";
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    private final WeChatProperties weChatProperties;
    private final UserMapper userMapper;
    private final JwtProperties jwtProperties;

    //用户登录
    public UserLoginVO login(UserLoginDTO dto){
        //1.登录请求
        String openid = getOpenid(dto.getCode());
        //2.查询是否是新用户
        User user = userMapper.getUserByOpenId(openid);
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }
        //3.生成token包装返回
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        return UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(openid)
                .build();
    }
    
    //发送post请求获取openId
    private String getOpenid(String code){
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code);
        JSONObject request = null;
        try {
            request = JSON.parseObject(HttpClientUtil.doPost(WX_LOGIN_URL, paramMap));
        } catch (IOException e) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        log.info("请求微信API:{}",request.toJSONString());
        return request.getString("openid");
    }
}
